<template>
  <div class="detection-record-container" id="detection-record-container">
    <div class="table-header">
      <a-button type="primary" @click="gotoView(1, {})">新增</a-button>
    </div>
    <div class="main">
      <vxe-table
        :data="tableData"
        show-overflow
        show-header-overflow
        show-footer-overflow
        :column-config="{ resizable: true }"
        class="scrollbarStyle"
        :sort-config="{ trigger: 'cell' }"
        ref="xTable"
        align="center"
      >
        <vxe-column type="seq" title="序号" width="80"></vxe-column>
        <vxe-column
          show-overflow
          :key="index"
          :title="item.title"
          :field="item.key"
          :width="item.width"
          v-for="(item, index) in columns"
        >
          <template #default="{ row }">
            <div v-if="item.key == 'result'">
              <div :class="[checkStatusClass(row), 'status-text']">
                {{ checkStatusName(row) }}
              </div>
            </div>
            <div v-else>{{ row[item.key] }}</div>
          </template>
        </vxe-column>
        <vxe-column
          field="operate"
          width="160"
          title="操作"
          fixed="right"
          align="left"
        >
          <template #default="{ row }">
            <div class="text-button-group">
              <a-button type="link" @click="gotoView(2, row)"> 详情 </a-button>
              <a-button type="link" @click="handleDelClick(row)" class="danger">
                删除
              </a-button>
            </div>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
    <div class="pager-container">
      <vxe-pager
        background
        :current-page.sync="pager.page"
        :page-size.sync="pager.pageSize"
        :total="pager.total"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes']"
        @page-change="paginationChange"
      >
        <template #left>
          <div class="vxe-pager-left-tip-container">
            第<span>1</span>到<span
              >{{ Math.ceil(pager.total / pager.pageSize) || 1 }}页 </span
            >共<span>{{ pager.total }}</span
            >条记录
          </div>
        </template>
      </vxe-pager>
    </div>

    <!-- 新增弹窗 -->
    <a-modal
      :visible="modalVisible"
      :maskClosable="false"
      :footer="null"
      width="780px"
      :title="modalTitle"
      wrapClassName="user-modal-container"
      @cancel="closeModal()"
      :getContainer="getContainer"
    >
      <div class="curve-modal-body">
        <!-- -->
        <a-form-model
          ref="form"
          :model="form"
          :rules="formRules"
          :hideRequiredMark="operate == 2 ? true : false"
        >
          <a-row :gutter="0">
            <a-col :span="24">
              <a-form-model-item label="检查结果" prop="result">
                <a-select
                  v-model="form.result"
                  :allowClear="true"
                  style="width: 160px"
                  placeholder="请选择检查结果"
                  :disabled="operate == 2 ? true : false"
                >
                  <a-select-option value="1"> 通过 </a-select-option>
                  <a-select-option value="2"> 不通过 </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="检查区域" prop="checkArea">
                <a-input
                  v-model.trim="form.checkArea"
                  placeholder="请填写检查区域"
                  :maxLength="200"
                  :disabled="operate == 2 ? true : false"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="检查内容" prop="content">
                <a-input
                  v-model.trim="form.content"
                  placeholder="请填写检查内容"
                  type="textarea"
                  :maxLength="500"
                  :rows="4"
                  :disabled="operate == 2 ? true : false"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="上传图片">
                <bjUploadImg
                  :viewMode="operate == 2 ? true : false"
                  :count="6"
                  v-model="form.imageList"
                  @change="upLoadImage($event)"
                  replaceField="imagePath"
                ></bjUploadImg>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
      <div class="curve-modal-footer">
        <a-button @click="closeModal()"> 取消</a-button>
        <a-button
          @click="submit()"
          type="primary"
          v-if="modalTitle == '新增'"
          :loading="buttonLoading"
        >
          确定
        </a-button>
      </div>
    </a-modal>
  </div>
</template>

<script>
import bjUploadImg from "@/components/bj-upload-img";
import {
  getRiskCheckList,
  getCheckSave,
  getRiskCheckDetail,
  getCheckDelete,
  filePath,
} from "@/api/wisdom-beam/security-app.js";
import { notificationTip } from "@/utils";
export default {
  name: "detectionRecord",
  components: {
    bjUploadImg,
  },
  props: {
    id: {
      type: [Number, String],
      default: "",
    },
  },
  watch: {
    id: {
      handler(val) {
        this.getTableData();
      },
      immediate: true,
    },
  },
  data() {
    return {
      columns: [
        {
          title: "检查时间",
          key: "updateTimeStr",
        },
        {
          title: "检查区域",
          key: "checkArea",
        },
        {
          title: "检查结果",
          key: "result",
        },
        {
          title: "检查部门",
          key: "zhgdDeptName",
        },
        {
          title: "检查人",
          key: "zhgdUserName",
        },
      ],
      tableData: [],
      pager: {
        page: 1,
        pageSize: 10,
        total: 0,
      },
      modalVisible: false,
      modalTitle: "新增",
      operate: 1,
      form: {
        //检查结果
        result: undefined,
        //检查区域
        checkArea: "",
        //检查内容
        content: "",
        //图片
        imageList: [],
      },
      formRules: {
        result: [
          {
            required: true,
            message: "请选择检查结果",
          },
        ],
        checkArea: [
          {
            required: true,
            message: "请填写检查区域",
          },
        ],
        content: [
          {
            required: true,
            message: "请填写检查内容",
          },
        ],
      },
      buttonLoading: false,
    };
  },
  mounted() {},
  methods: {
    //modal 挂载节点
    getContainer() {
      return document.getElementById("dashboard-container");
    },
    gotoView(type, row) {
      this.operate = type;
      this.modalTitle = type == 2 ? "详情" : "新增";
      this.modalVisible = true;
      let { id } = row;
      if (id) {
        this.getDetail(row);
      }
    },
    //上传图片
    upLoadImage({ file, index }) {
      this.$set(this.form["imageList"][index], "loading", true);
      setTimeout(() => {
        this.$set(this.form["imageList"][index], "loading", false);
      }, 500);
    },
    //详情
    getDetail(row) {
      let { id } = row;
      getRiskCheckDetail(id)
        .then((res) => {
          let { data } = res;
          this.form.result = data.result?.result;
          this.form.checkArea = data.result?.checkArea;
          this.form.content = data.result?.content;
          let list = data.result.fileList || [];
          list.forEach((v) => {
            filePath(v.id)
              .then((res) => {
                this.$set(v, "imagePath", res.data?.result || "");
              })
              .catch((_) => {});
          });
          this.form.imageList = list;
        })
        .catch();
    },
    submit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.buttonLoading = true;
          let { form } = this;
          let formJson = {
            //检查结果
            result: form.result,
            //检查区域
            checkArea: form.checkArea,
            //检查内容
            content: form.content,
            //主键id
            dangerId: this.id,
          };
          let formdata = new FormData();
          Object.entries(formJson).forEach(([key, value]) => {
            formdata.append(key, value);
          });
          //图片
          if (form.imageList.length > 0) {
            for (let i = 0; i < form.imageList.length; i++) {
              if (form.imageList[i].file) {
                formdata.append("uploadFile", form.imageList[i].file);
              } else {
                formdata.append("uploadFile", new File([], "file"));
              }
            }
          } else {
            formdata.append("uploadFile", new File([], "file"));
          }
          getCheckSave(formdata)
            .then((res) => {
              this.closeModal();
              this.getTableData();
              notificationTip("success", "新增成功!");
            })
            .catch((_) => {})
            .finally((_) => {
              this.buttonLoading = false;
            });
        }
      });
    },
    closeModal() {
      this.modalVisible = false;
      this.form = {
        //检查结果
        result: undefined,
        //检查区域
        checkArea: "",
        //检查内容
        content: "",
        //图片
        imageList: [],
      };
      this.$refs.form.resetFields();
    },
    //获取表格数据
    getTableData() {
      let { page, pageSize } = this.pager;
      getRiskCheckList({
        dangerId: this.id,
        page,
        pageSize,
      })
        .then((res) => {
          let { data } = res;
          this.tableData = data?.result?.rows || [];
          this.pager.total = data?.result?.total || 0;
        })
        .catch((_) => {
          this.tableData = [];
          this.pager.total = 0;
        });
    },
    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getTableData();
    },
    //删除
    handleDelClick(row) {
      let dataLength = this.tableData.length;
      let that = this;
      const h = this.$createElement;
      this.$confirm({
        title: "您确定删除所选内容?",
        content: "删除内容后,将无法恢复。",
        okText: "确定",
        okType: "primary",
        cancelText: "取消",
        centered: true,
        icon: () =>
          h("a-icon", {
            props: {
              type: "question-circle",
              theme: "filled",
            },
            style: "color:#FB5A5A",
          }),
        onOk() {
          getCheckDelete(row.id)
            .then((res) => {
              if (dataLength == 1 && that.pager.page > 1) {
                that.pager.page -= 1;
              }
              notificationTip("success", "删除成功！");
              that.getTableData();
            })
            .catch();
        },
        onCancel() {},
      });
    },
    //校验状态名称
    checkStatusName(row) {
      let { result } = row;
      switch (result) {
        case "1":
          return "通过";

        case "2":
          return "不通过";

        default:
          return "--";
      }
    },
    //校验状态className
    checkStatusClass(row) {
      let { result } = row;
      switch (result) {
        case "1":
          return "normal";

        case "2":
          return "error";

        default:
          return "cancel";
      }
    },
  },
};
</script>

<style lang="less" scoped>
.detection-record-container {
  overflow: hidden;
  .flex();
  flex-direction: column;
  .table-header {
    margin-bottom: 10px;
    .flex();
    flex-direction: row-reverse;
  }
  .status-text {
    border-radius: 4px;
    color: #fff;
    .flex();
    align-items: center;
    justify-content: center;
    margin: 0 auto;
    font-size: 12px;
    width: 80px;
    &.lock {
      background: #0098ff;
    }
    &.warn {
      background: #ff993f;
    }
    &.approv {
      background: #ff7113;
    }
    &.normal {
      background: #4bc964;
    }
    &.error {
      background: #ff3f4a;
    }
    &.cancel {
      background: #f1f2f7;
      color: #aab0bc;
    }
  }
  .pager-container {
    flex-shrink: 0;
    background-color: #fff;
  }
}
/deep/.bj-upload-img {
  margin-top: 12px;
}

/deep/.user-modal-container {
  .ant-modal-body {
    padding: 0;
  }
  .curve-modal-body {
    padding: 20px 60px 0px 20px;
    max-height: 600px;
    .custom-scrollbar();
  }
  .curve-modal-footer {
    padding-bottom: 20px;
    .flex();
    align-items: center;
    justify-content: center;
    button {
      &:last-child {
        margin-left: 20px;
      }
    }
  }
}
/deep/.ant-form-item {
  display: flex;
  .ant-form-item-label {
    width: 100px;
    min-width: 100px;
    white-space: pre-wrap;
    display: flex;
    justify-content: flex-end;
    line-height: 20px;
    align-items: center;
    margin-right: 10px;
    height: 36px;
    label {
      color: #999999;
    }
  }
  .check-item-select {
    height: 126px;
    .ant-select-selection__rendered {
      height: 126px;
      .ant-select-selection__placeholder {
        margin-top: -40px !important;
      }
    }
  }
  .ant-select {
    width: 100% !important;
    min-width: unset !important;
  }
  .ant-form-item-control-wrapper {
    flex: 1;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}
</style>
